package com.xx.springsecuritydemo.main.security;

import com.xx.springsecuritydemo.main.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CustomSecurityMetadataSource2 implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private IRoleService roleService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestURI = ((FilterInvocation) object).getRequest().getRequestURI();

        // 2. 查询数据库中的权限信息
        List<String> permissions = roleService.getRoleNameByUrl(requestURI);

        // 3. 如果查询到权限，返回权限列表
        if (permissions != null && !permissions.isEmpty()) {
            return permissions.stream()
                    .map(SecurityConfig::new)
                    .collect(Collectors.toList());
        }

        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return Collections.emptyList();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
